// src/composables/StationUsePileForm.js

import { ref, reactive } from 'vue';
import {ElMessage} from "element-plus";

export function stationUsePileForm() {
    const pileDialogVisible = ref(false);
    const pileForm = reactive({
        id: '',
        pileName: '',
        pileCode: '',
        pileType: '',
        pilePower: 0,
        pileModel: '',
        pileDesc: '',
        pileStatus: '空闲中',
        suitableVehicle: '',
        pileImgUrl: '',
    });
    const isAddingPile = ref(true);

    // 打开弹窗
    const openPileDialog = (pile = null) => {
        if (pile) {
            Object.assign(pileForm, pile);
            isAddingPile.value = false;
        } else {
            Object.assign(pileForm, {
                id: '',
                pileName: '',
                pileCode: '', // 确保新增时有唯一的 pileCode
                pileType: '',
                pilePower: 0,
                pileModel: '',
                pileDesc: '',
                pileStatus: '空闲中',
                suitableVehicle: '',
                pileImgUrl: '',
            });
            isAddingPile.value = true;
        }
        pileDialogVisible.value = true;
    };


    // 保存充电桩
    const savePile = (chargingPiles) => {
        console.log("保存前的 chargingPiles：", chargingPiles); // 调试
        console.log("当前 pileForm：", pileForm); // 调试

        if (isAddingPile.value) {
            // 新增逻辑
            if (!pileForm.pileCode) {
                pileForm.pileCode = `pile_${Date.now()}`; // 生成唯一 pileCode
            }
            chargingPiles.push({ ...pileForm });
            ElMessage.success("新增充电桩成功");
        } else {
            // 编辑逻辑
            const index = chargingPiles.findIndex((p) => p.pileCode === pileForm.pileCode);
            if (index !== -1) {
                chargingPiles.splice(index, 1, { ...pileForm });
                ElMessage.success("编辑充电桩成功");
            } else {
                ElMessage.error("编辑失败：未找到本地的充电桩");
                console.error("保存失败 - 当前 pileForm：", pileForm);
                console.error("保存失败 - 本地 chargingPiles：", chargingPiles);
            }
        }

        // 强制触发响应式更新
        chargingPiles = [...chargingPiles];

        // 关闭弹窗
        pileDialogVisible.value = false;
    };


    // 删除充电桩
    const removePile = (chargingPiles, index) => {
        chargingPiles.splice(index, 1);
    };

    return {
        pileDialogVisible,
        pileForm,
        isAddingPile,
        openPileDialog,
        savePile,
        removePile,
    };
}
